// -*- mode:C; tab-width:2; indent-tabs-mode:nil;  -*-
// $Id: atomic_int.c,v 1.7 2010/04/22 16:55:42 zahorjan Exp $

#include <pthread.h>

#include "atomicInt.h"
#include "lockDef.h"

#include "factory.h"

INSTANTIATETYPE(atomic_int_t, int intValue; pthread_mutex_t lock;)
CREATEMANAGER(atomic_int_t)

int atomic_int_create( atomic_int_t* a, int initialValue) { // returns 0 for success
  *a = atomic_int_t_acquire();
  (*a)->intValue = initialValue;
  pthread_mutex_init(&((*a)->lock), NULL);
  return 0;
}

void atomic_int_destroy( atomic_int_t a ) {
  atomic_int_t_release(a, NULL);
}

int atomic_int_getValue( atomic_int_t a) {
  return a->intValue;
}

// these all return the value of the atomic int, with semantics like ++i vs. i++
int atomic_int_preIncrement( atomic_int_t a) {
  pthread_mutex_lock(&(a->lock));
  int result = a->intValue++;
  pthread_mutex_unlock(&(a->lock));
  return result;
}

int atomic_int_postIncrement( atomic_int_t a) {
  pthread_mutex_lock(&(a->lock));
  int result = ++a->intValue;
  pthread_mutex_unlock(&(a->lock));
  return result;
}

int atomic_int_preDecrement( atomic_int_t a) {
  pthread_mutex_lock(&(a->lock));
  int result = a->intValue--;
  pthread_mutex_unlock(&(a->lock));
  return result;
}

int atomic_int_postDecrement( atomic_int_t a) {
  pthread_mutex_lock(&(a->lock));
  int result = --a->intValue;
  pthread_mutex_unlock(&(a->lock));
  return result;
}


